14. Experimenting in Interactive Mode

Experimenting in Interactive Mode

We can experiment with our app using the interactive mode of the Python interpreter.

You've undoubtedly used Python interactive mode before, which you can get to by simply starting your terminal and entering python3 :

$ python3
Python 3.7.3 (default, Mar 27 2019, 16:54:48) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Let's see how we can use this to experiment with our SQLAlchemy apps!

ND004 C01 L03 12 SQLAlchemy(App) Db.Model And Db.Create All() Part 2

Code

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://udacitystudios@localhost:5432/example'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Person(db.Model):
  __tablename__ = 'persons'
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(), nullable=False)

db.create_all()

@app.route('/')
def index():
  person = Person.query.first()
  return 'Hello ' + person.name

Follow along

Follow along

Task Description:

Before going further, be sure you've tried the following:

Task List:

Task Feedback:

Great!

Now let's see what we can do from interactive mode.

Code

Try running this yourself in the terminal.

$ python3
>>> from flask_hello_app import Person, db
>>> Person.query.all()
>>> Person.query.first()
>>> query = Person.query.filter(Person.name == 'Amy')
>>> query.first()
>>> query.all()

Debugging

ND004 C01 L03 13 SQLAlchemy(App) Db.Model And Db.Create All() Part 3

Code

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://udacitystudios@localhost:5432/example'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Person(db.Model):
  __tablename__ = 'persons'
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(), nullable=False)

  def __repr__(self):
    return f'<Person ID: {self.id}, name: {self.name}>'

db.create_all()

@app.route('/')
def index():
  person = Person.query.first()
  return 'Hello ' + person.name

Try this on your own machine

Task Description:

Here's what you can try to practice printing debugging statements

Task List:

Task Feedback:

Awesome! Great job on doing this practice.

Now try this: create records in python's interactive mode using db.session.add()

There's another way of inserting records into our database, rather than entering a client like psql and using INSERT INTO SQL commands: we can call db.session from SQLAlchemy to create records using instances of our defined SQLAlchemy models.

In interactive mode, import db and your Person model.

$ cd YOUR_PROJECT_DIRECTORY
$ python3
>>> from flask_hello_app import db, Person

Then, create an instance of a Person , setting its attributes, and setting it equal to a variable person

>>> person = Person(name='Amy')

We're going to call db.session.add() , a method on the Session interface in SQLAlchemy, to add this object to a session,

>>> db.session.add(person)

This will queue up a INSERT INTO persons (name) VALUES ('Amy'); statement in a transaction that is managed by db.session .

We can then call db.session.commit()

>>> db.session.commit()

and that person record will now exist in our persons table, within our database! You can double-check this in psql by running a SELECT * from persons; command from psql.

In summary

We can insert new records into the database using SQLAlchemy by running

person = Person(name='Amy')
db.session.add(person)
db.session.commit()

which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit() .

Workspace Option

You can try out these steps using the interactive workspace below, instead of using your own machine.

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter-lab
  • Opened files (when workspace is loaded): n/a